package com.zyasdk.handler;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.zhuoyian.analysis.util.AppUtils;
import com.zhuoyian.analysis.util.StaticSettings;
import com.zyasdk.VUpdateUtil;
import com.zyasdk.model.ARModel;
import com.zyasdk.model.Packages;
import com.zyasdk.util.JSONHelper;
import com.zyasdk.util.ZYALogUtils;

/**
 * context handler
 * 
 * @author Administrator
 * 
 */
public class VersionHandler extends Handler {

	/**
	 * msg update version
	 */
	public final static int UPDATE_VERSION = 1000;
	/**
	 * get root is running
	 */
	public static boolean getr_is_running = false;
	/**
	 * Activity
	 */
	public Activity mCon;

	/**
	 * Construction method
	 * @param context
	 */
	public VersionHandler(Activity context) {
		super();
		this.mCon = context;
	}

	/**
	 * Construction method
	 * @param context
	 * @param callback
	 */
	public VersionHandler(Activity context, Callback callback) {
		super(callback);
		this.mCon = context;
	}

	/**
	 * handler message
	 */
	@Override
	public void handleMessage(Message msg) {
		super.handleMessage(msg);
		if (mCon == null) {
			return;
		}
		switch (msg.what) {
		// 获得是否更新数据
		case StaticSettings.RESULT_OK:
			Bundle bund = msg.getData();
			ARModel model = (ARModel) bund.getSerializable("result");
			Log.i("ConHandler", "model=" + model.toString());
			if (model != null && !TextUtils.isEmpty(model.getReusltContent())) {
				if (model.getResultCode().equals(ARModel.RESULT_OK)) {
					JSONObject obj;
					ZYALogUtils.e(model.getReusltContent());
					Packages ver = null;
					try {
						obj = new JSONObject(model.getReusltContent());
						ver = JSONHelper.parseObject(obj, Packages.class);
					} catch (JSONException e) {
						e.printStackTrace();
					}
					if (ver == null || TextUtils.isEmpty(ver.getPath())
							|| ver.getLevel() == 0) {
						return;
					}

					if (ver != null) {
						//down new version
						ver.setOldVersion(AppUtils.getVersionCode(mCon));
						VUpdateUtil.download(ver);
					}
				}
			}
			break;
		// 更新下载进度
		case UPDATE_VERSION:
			if (msg.obj == null) {
				return;
			}
			// 提示更新
			VUpdateUtil.hintUpdateVersion(mCon, ((String) msg.obj));
			break;
		}
	}
}
